package cn.imvc.app.models;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.domains.Constants;
import cn.imvc.app.domains.EditMobileOrEmail;
import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Dealer;
import cn.imvc.app.entities.Member;
import cn.imvc.core.ICache;
import cn.imvc.core.Render;
import cn.imvc.util.CompressPic;
import cn.imvc.util.Md5;
import cn.imvc.util.ToolUtils;

@Service
public class SettingModelImpl implements SettingModel {
	
	private Logger logger = Logger.getLogger(SettingModelImpl.class);

	@Autowired
	private MemberModel memberModel;

	@Autowired
	private AccountModel accountModel;

	@Autowired
	private DealerModel dealerModel;

	@Autowired
	SystemConfig systemConfig;

	@Autowired
	ICache cache;

	public Map<String, String> updatePw(String token, String oldpw, String newpw, String key1) {
		Map<String, String> result = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		result.put("code", "0");
		if (StringUtils.isEmpty(oldpw)) {
			result.put("msg", "原密码为空");
			return result;
		} else if (StringUtils.isEmpty(newpw)) {
			result.put("msg", "新密码为空");
			return result;
		} else if (StringUtils.isEmpty(key1)) {
			result.put("msg", "系统异常，请稍后再试！");
			logger.error("修改密码：" + member.getLoginname() + "，key1为空，result:" + Render.json(result));
			return result;
		}
		String key2 = member.getKey2();
		if (Md5.encode(oldpw + key2).equals(member.getPasswd())) {
			member.setPasswd(Md5.encode(newpw + key2));
			memberModel.save(member);
			memberModel.updateLoginMember(member, token);
			result.put("code", "1");
			result.put("msg", "修改成功");
		} else {
			result.put("msg", "原密码不正确");
		}
		return result;
	}

	public Map<String, String> updatePayPw(String loginname, String messagecode, String token, String paypw, String key1) {
		Map<String, String> result = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		if (StringUtils.isEmpty(paypw)) {
			result.put("msg", "新密码为空");
			return result;
		} else if (StringUtils.isEmpty(key1)) {
			result.put("msg", "系统异常，请稍后再试！");
			logger.error("修改支付密码：" + member.getLoginname() + "，key1为空，result:" + Render.json(result));
			return result;
		}
		member = memberModel.get(member.getId());
		Account account = accountModel.get(member.getAccount().getId());
		try {
			accountModel.checkAccount(account);
		} catch (Exception e) {
			result.put("msg", "账户异常");
			return result;
		}
		boolean checkcode = memberModel.checkCodeError(loginname);
		if(checkcode){
			checkcode = memberModel.checkMessageCode(messagecode, loginname);
		}
		if (checkcode) {
			if (account != null) {
				String key2 = account.getKey2();
				if (StringUtils.isEmpty(key2)) {
					key2 = Md5.encode(String.valueOf(System.currentTimeMillis()));
				}
				account.setKey2(key2);
				account.setPaypwd(Md5.encode(paypw + key2));
				accountModel.save(account);
				result.put("code", "1");
				result.put("msg", "修改成功");
				cache.remove(Constants.CACHENAME_MEMBER, Constants.MESSAGE_CODE_KEY_PREFIX + loginname);
			} else {
				result.put("msg", "系统异常");
			}
		} else {
			result.put("msg", "验证码不正确");
		}
		return result;
	}

	public Map<String, String> updateName(String name, String token) {
		Map<String, String> result = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		member = memberModel.get(member.getId());
		member.setName(name);
		member = memberModel.save(member);
		memberModel.updateLoginMember(member, token);
		Dealer dealer = member.getDealer();
		if(dealer != null){
			dealer.setName(name);
			dealerModel.save(dealer);
		}
		result.put("code", "1");
		result.put("msg", "修改成功");
		return result;
	}

	public Map<String, String> updateSex(int sex, String token) {
		Map<String, String> result = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		member.setSex((byte) sex);
		member = memberModel.save(member);
		memberModel.updateLoginMember(member, token);
		result.put("code", "1");
		result.put("msg", "修改成功");
		return result;
	}

	public Map<String, String> updateMobileOrEmail(String token, EditMobileOrEmail entity) {
		String loginname = entity.getLoginname();
		String type = entity.getType();
		String verify = entity.getVerify();
		String account = entity.getAccount();
		String code = entity.getCode();
		String newcode = entity.getNewcode();
		Map<String, String> result = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		if (StringUtils.isEmpty(type) || StringUtils.isEmpty(verify)) {
			result.put("msg", "系统异常");
			return result;
		}
		if (StringUtils.isEmpty(code)) {
			result.put("msg", "验证码不能为空");
			return result;
		}
		if (StringUtils.isEmpty(account)) {
			if ("0".equals(type)) {
				result.put("msg", "新手机号不能为空");
				return result;
			} else if ("1".equals(type)) {
				result.put("msg", "新邮箱地址不能为空");
				return result;
			}
		} else {
			if("0".equals(type) && "0".equals(verify) && account.equals(loginname)){
				result.put("msg", "新手机号与原手机号相同");
				return result;
			}
			if("1".equals(type) && "1".equals(verify) && account.equals(loginname)){
				result.put("msg", "新邮箱与原邮箱相同");
				return result;
			}
			if ("0".equals(type) && !ToolUtils.isMobile(account)) {
				result.put("msg", "新的手机号格式不正确");
				return result;
			} else if ("1".equals(type) && !ToolUtils.isEmail(account)) {
				result.put("msg", "新的邮箱地址格式不正确");
				return result;
			}
			if("0".equals(type)){
				Member isExists = memberModel.getByLoginname(account);
				if (isExists != null) {
					result.put("msg", "手机号已存在");
					return result;
				}
			}
			if("1".equals(type)){
				List<Member> list = memberModel.findByEmail(account);
				if(list != null && list.size() > 0){
					result.put("msg", "邮箱已存在");
					return result;
				}
			}
		}
		if (StringUtils.isEmpty(newcode)) {
			result.put("msg", "新账号验证码不能为空");
			return result;
		}
		boolean check = false;
		if ("0".equals(verify)) {
			check = memberModel.checkMessageCode(code, loginname);
		} else if ("1".equals(verify)) {
			check = memberModel.checkEmailCode(code, loginname);
		}
		boolean newcheck = false;
		if ("0".equals(type)) {
			newcheck = memberModel.checkCodeError(loginname);
			if(newcheck){
				newcheck = memberModel.checkMessageCode(newcode, account);
			} else {
				result.put("msg", "系统异常，请稍后再试");
				return result;
			}
		} else if ("1".equals(type)) {
			newcheck = memberModel.checkEmailCode(newcode, account);
		}
		if (check) {
			if(newcheck){
				if ("0".equals(type)) {
					member.setMobile(account);
					member.setLoginname(account);
				} else if ("1".equals(type)) {
					member.setEmail(account);
				}
			} else {
				if("0".equals(type)){
					result.put("msg", "新手机号验证码不正确");
				} else {
					result.put("msg", "新邮箱验证码不正确");
				}
				return result;
			}
			memberModel.save(member);
			memberModel.updateLoginMember(member, token);
			if ("0".equals(type)) {
				if ("0".equals(verify)) {
					cache.remove(Constants.CACHENAME_MEMBER, Constants.MESSAGE_CODE_KEY_PREFIX + loginname);
				} else if ("1".equals(verify)) {
					cache.remove(Constants.CACHENAME_MEMBER, Constants.EMAIL_CODE_KEY_PREFIX + loginname);
				}
				cache.remove(Constants.CACHENAME_MEMBER, Constants.MESSAGE_CODE_KEY_PREFIX + account);
			} else if ("1".equals(type)) {
				if ("0".equals(verify)) {
					cache.remove(Constants.CACHENAME_MEMBER, Constants.MESSAGE_CODE_KEY_PREFIX + loginname);
				} else if ("1".equals(verify)) {
					cache.remove(Constants.CACHENAME_MEMBER, Constants.EMAIL_CODE_KEY_PREFIX + loginname);
				}
				cache.remove(Constants.CACHENAME_MEMBER, Constants.EMAIL_CODE_KEY_PREFIX + account);
			}
			result.put("code", "1");
			result.put("msg", "修改成功");
			return result;
		} else {
			if("0".equals(type)){
				result.put("msg", "手机号验证码不正确");
			} else {
				result.put("msg", "邮箱验证码不正确");
			}
			return result;
		}
	}

	public Map<String, String> updateAvatar(String token, MultipartFile photo) {
		Map<String, String> result = upload(photo, systemConfig.getUserImageFolder());
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			String code = result.get("code");
			if ("1".equals(code)) {
				String dic = result.get("fileUrl");
				member.setAvatar(dic);
				memberModel.save(member);
				memberModel.updateLoginMember(member, token);
			}
		} else {
			result.put("code", "-1");
			result.put("msg", "请登录");
		}
		return result;
	}

	public Map<String, String> upload(MultipartFile photo, String path) {
		String dicPath = systemConfig.getImagePath() + path + File.separator + ToolUtils.getDateFormat(new Date(), "yyyyMMdd");
		Map<String, String> result = new HashMap<String, String>();
		String fileName = photo.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = Md5.encode(System.currentTimeMillis() + fileName) + suffix;
		// 临时文件名，压缩之后删除
		String temporaryFileName = Md5.encode(ToolUtils.getUUID() + fileName) + suffix;
		File temporaryFile = new File(dicPath, temporaryFileName);
		if (!temporaryFile.exists()) {
			temporaryFile.mkdirs();
		}
		try {
			photo.transferTo(temporaryFile);
			boolean up;
			// 头像上传压缩为宽度300，高度等比例，评论及退货上传图片压缩为宽度700，高度等比例
			if(systemConfig.getUserImageFolder().equals(path)){
				up = CompressPic.compressPic(temporaryFile, dicPath + File.separator + newFileName, 300);
			} else {
				up = CompressPic.compressPic(temporaryFile, dicPath + File.separator + newFileName, 700);
			}
			if(!up){
				result.put("code", "0");
				result.put("msg", "上传失败");
				return result;
			}
			String serverPath = dicPath.replace(systemConfig.getImagePath(), systemConfig.getImageDomain()) + File.separator + newFileName;
			serverPath = serverPath.replace(File.separator, "/");
			result.put("fileUrl", serverPath);
			result.put("code", "1");
			result.put("msg", "上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "0");
			result.put("msg", "上传失败");
		}
		return result;
	}
}
